#include "head.h"

// cd
int cd(me_t* me, int sock_fd, char* cmd)
{
    messenger_t msg;
    bzero(&msg, sizeof(msg));

    msg.cmd = CD;
    while(*cmd++ != ' ');

    // 判断是否为返回上级目录
    if(strcmp(cmd, "..") == 0)
    {
        char* tail = me->path;
        while(*tail != '\0')  ++tail;
        while(*tail !='/')  --tail;
        bzero(tail, strlen(tail));

        // 判断是否已经到了根目录
        if(strlen(me->path) == 0)
        {
            strcat(me->path, "/");
            return 0;
        }
        else
            return 0;
    }
    if(strcmp(cmd, ".") == 0)
        return 0;

    sprintf(msg.args, "%s&%s", me->path, cmd);
    sprintf(msg.token, "%s", me->token);
    send(sock_fd, &msg, sizeof(msg), MSG_NOSIGNAL);
    printf("args: %s\n", msg.args);

    char reply[20] = {0};
    recv(sock_fd, reply, sizeof(reply), 0);

    if(strcmp(reply, "succeed") == 0)
    {
        if(strcmp(me->path, "/") == 0)
            strcat(me->path, cmd);
        else
        {
            strcat(me->path, "/");
            strcat(me->path, cmd);
        }

        return 0;
    }

    // 成功
    printf("没有这个文件夹\n");
    return -1;
}